package cn.iocoder.yudao.module.voice.cc.websocket;

import cn.iocoder.yudao.framework.common.util.CheckUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zhongweixian.entity.Message;
import org.zhongweixian.listener.ConnectionListener;
import org.zhongweixian.server.websocket.WebSocketServerHandler;

import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

public class WsServerHandler  extends SimpleChannelInboundHandler<WebSocketFrame> {
    private Logger logger = LoggerFactory.getLogger(WebSocketServerHandler.class);
    private Integer heart;
    private ListenerCallBack listener;

    public WsServerHandler(Integer heart, ListenerCallBack listener) {
        this.heart = heart;
        this.listener = listener;
    }

    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
         if (msg instanceof TextWebSocketFrame) {
            TextWebSocketFrame frame = (TextWebSocketFrame)msg;

            try {
                JSONObject jsonObject = JSONObject.parseObject(frame.text());
                if (jsonObject == null) {
                    return;
                }

                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("received client:{}, message:{}", ctx.channel().id(), jsonObject);
                }

                if (!"ping".equals(jsonObject.getString("cmd"))) {
                    if (jsonObject != null) {
                        Boolean result = this.listener.callback(ctx.channel(),jsonObject.getString("token"));
                        if(result){
                            this.listener.onMessage(ctx.channel(), frame.text());
                        }
                    }
                    return;
                }

                ctx.channel().writeAndFlush(new TextWebSocketFrame("{\"type\":\"pong\",\"status\":0,\"sequence\":" + Instant.now().toEpochMilli() + "}"));
            } catch (Exception var10) {
                this.logger.error("解析json:{} 异常", frame.text(), var10);
                JSONObject error = new JSONObject();
                error.put("messgae", var10.getMessage());
                error.put("code", 500);
                ctx.channel().writeAndFlush(new TextWebSocketFrame(error.toJSONString()));
            } finally {
                super.channelRead(ctx, msg);
            }

        }
    }

    protected void channelRead0(ChannelHandlerContext channelHandlerContext, WebSocketFrame webSocketFrame) throws Exception {
    }

    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelActive();
    }

    public void channelInactive(ChannelHandlerContext ctx) {
        this.logger.error("websocket client :{}, inactive : {}", ctx.channel().id(), ctx.channel().isActive());
        this.listener.onClose(ctx.channel(), 500, "channelInactive");
    }

    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        this.logger.error("websocket client:{}  exceptionCaught:{} ", ctx.channel().id(), cause);
        this.listener.onClose(ctx.channel(), 501, cause.getMessage());
    }

    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        this.logger.debug("websocket client:{} , connect success", ctx.channel().id());
        this.listener.callback(ctx.channel());
        ctx.fireChannelRegistered();
    }

    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent)evt;
            switch (idleStateEvent.state()) {
                case READER_IDLE:
                    if (this.heart <= 0) {
                        return;
                    }

                    this.logger.warn("No heartbeat message received in {} seconds", this.heart);
                    Message message = new Message();
                    message.setType("timeout");
                    message.setCode("10005");
                    message.setMessage("no heartbeat message received in " + this.heart + " seconds , channel closed");
                    ctx.channel().writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(message)));
                    ctx.close();
                case WRITER_IDLE:
            }
        }

        super.userEventTriggered(ctx, evt);
    }

    private static Map getUrlParams(String url) {
        Map<String, String> map = new HashMap();
        url = url.replace("?", ";");
        if (!url.contains(";")) {
            return map;
        } else if (url.split(";").length <= 0) {
            return map;
        } else {
            String[] arr = url.split(";")[1].split("&");
            String[] var3 = arr;
            int var4 = arr.length;

            for(int var5 = 0; var5 < var4; ++var5) {
                String s = var3[var5];
                String key = s.split("=")[0];
                String value = s.split("=")[1];
                map.put(key, value);
            }

            return map;
        }
    }

}
